<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form">
          <template #FeeType>
            <el-select v-model="form.fee_type" style="max-width: 200px" clearable placeholder="费用类型">
              <el-option-group v-for="group in freeType" :key="group.label" :label="group.label">
                <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value" />
              </el-option-group>
            </el-select>
          </template>
          <template #WarehouseSelect>
            <WarehouseSelect v-model:modelValue="form.shipping_warehouse_id" multiple placeholder="发货仓库" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <el-button icon="Plus" type="primary" @click="add" v-hasPermi="[basicSetupAuthList.custom_fee_items.add]">新增</el-button>
        <el-button @click="handleStatus(1)" v-hasPermi="[basicSetupAuthList.custom_fee_items.enable]">
          <div class="dk-iconfont icon-CircleCheck text-[#3487FF]"></div>
          启用
        </el-button>
        <el-button @click="handleStatus(0)" v-hasPermi="[basicSetupAuthList.custom_fee_items.disable]">
          <div class="dk-iconfont icon-Disabled text-[red]"></div>
          禁用
        </el-button>
      </template>
    </VTable>

    <!-- <VLog ref="logRef" :api="oplog"></VLog> -->
    <!-- 日志/ -->
    <Log dialog v-model="logVisible" :autoLoad="false" tag="custom_cost" :business_id="logId" />

    <Vedit
      ref="edit"
      :title="editTitle"
      class="dialogPublic"
      :sharingRules="sharingRules"
      :orderShippingType="orderShippingType"
      :freeType="freeType"
      @confirm="editConfirm"
      :originOption="originOption"
    />
    <Vtransport ref="transport" class="dialogPublic"></Vtransport>
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import { organizationList, overallOptions } from "@/api/public"
import { queryList, oplog, getFreeType, setStatus } from "./api"
import { ElMessage } from "element-plus"
import { onMounted, ref, toRefs } from "vue"
import { basicSetupAuthList } from "@/Auth/basic-setup.js"

import XForm from "@/components/XForm/index.vue"
import WarehouseSelect from "@/components/WarehouseSelect/index.vue"
import VLog from "@/components/VLog"
import Vedit from "./components/edit"
import Vtransport from "./components/transport"
const transport = ref()
const edit = ref()
const data = reactive({
  editTitle: "新增",
  statusOption: [],
  billingMethod: [],
  orderShippingType: [],
  sharingRules: [],
  freeType: [],
})
const { editTitle, statusOption, billingMethod, orderShippingType, sharingRules, freeType } = toRefs(data)
const tableRef = ref()

// 日志
import Log from "@/components/Log/index.vue"

const logVisible = ref(false)
const logId = ref("")
const openLog = (row) => {
  logId.value = row.id
  logVisible.value = true
}

//编辑
const ruleEdit = (row) => {
  editTitle.value = "编辑"
  edit.value.open(row)
}
//新增
const add = () => {
  editTitle.value = "新增"
  edit.value.open()
}
const editConfirm = () => {
  query()
}
//启用
const handleStatus = (status) => {
  if (!getSelectRow().length) {
    return false
  }
  const arr = getSelectRow()
  setStatus({ ids: arr, status }).then((res) => {
    ElMessage({
      message: "操作成功",
      type: "success",
    })
    query()
  })
}

// 查询
const query = () => {
  tableRef?.value.query()
}
//获取下拉数据
onMounted(() => {
  getWarehouseEnumList()
  overallOptions({ params: ["base.customCostItem"] }).then((res) => {
    statusOption.value = res.data.baseCustomCostItem.status
    billingMethod.value = res.data.baseCustomCostItem.billing_method
    orderShippingType.value = res.data.baseCustomCostItem.order_shipping_type
    sharingRules.value = res.data.baseCustomCostItem.sharing_rules
  })
  getFreeType().then((res) => {
    freeType.value = res.data
  })
})
const originOption = ref({})
import { getWarehouseEnum } from "@/api/public"
const getWarehouseEnumList = async () => {
  try {
    const res = await getWarehouseEnum()
    originOption.value.warehouseOpt = res.data.wms_attribute
  } catch (e) {
    throw Error(e)
  }
}

const formOption = ref({
  inline: true,
})
const publicStyle = { style: { width: "180px" } }
const fieldList = ref([
  {
    field: "fee_type",
    slot: "FeeType",
    ...publicStyle,
  },
  {
    field: "billing_method",
    type: "select",
    options: {
      placeholder: "计费方式",
      data: billingMethod,
    },
    ...publicStyle,
  },
  {
    field: "shipping_type",
    type: "select",
    options: {
      placeholder: "发货类型",
      data: orderShippingType,
    },
    ...publicStyle,
  },
  {
    field: "shipping_warehouse_id",
    slot: "WarehouseSelect",
    style: { width: "200px" },
  },
  {
    field: "status",
    type: "select",
    options: {
      placeholder: "状态",
      data: statusOption,
    },
    style: { width: "120px" },
  },
  {
    field: "fee_description",
    placeholder: "费用说明",
    ...publicStyle,
  },
  {
    field: "create_user",
    type: "cascader",
    itemProps: { placeholder: "添加人" },
    ...publicStyle,
  },
  {
    field: "dateRange",
    type: "dateTimeRangeNorm",
    select: [{ label: "创建时间", value: "create_time" }],
    selectStyle: { width: "100px" },
  },
])

//获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}
//获取文本
const getText = (arr, val) => {
  return arr?.find((v) => v.value == val)?.label || ""
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      fee_type: "",
      billing_method: "",
      shipping_type: "",
      shipping_warehouse_id: [],
      status: "",
      fee_description: "",
      create_user: "",
      dateRange: { type: "create_time", value: [], range: true }, // 组合+日期范围
    },
  },
  showOverflow: true,
  tooltipConfig: {
    showAll: false,
  },
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },
    { field: "id", title: "ID", width: 60 },
    { field: "fee_type_text", title: "费用类型", width: 180 },
    {
      field: "billing_method",
      title: "计费方式",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText value={getText(billingMethod.value, row.billing_method)} line={1} />
            </div>
          )
        },
      },
    },
    { field: "fee_description", title: "费用说明", minWidth: 140 },
    { field: "priority", title: "优先级", minWidth: 80 },
    { field: "order_shipping_type_text", title: "发货类型", minWidth: 200 },
    {
      field: "shipping_warehouse",
      title: "发货仓库",
      minWidth: 100,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {row.shipping_type == 1 ? (
                <div>{originOption.value.warehouseOpt.find((v) => v.value == row.warehouse_type)?.label}</div>
              ) : (
                <el-button type="primary" link onClick={() => transport.value.open(row.shipping_warehouse)}>
                  查看
                </el-button>
              )}
            </div>
          )
        },
      },
    },
    { field: "fee_unit_price", title: "费用单价(RMB)", minWidth: 120 },
    {
      title: "状态",
      field: "status_text",
      width: 100,
      slots: {
        default: ({ row }) => <VStatus value={!!row.status} />,
      },
    },

    { field: "create_user", title: "创建人", width: 150 },
    { field: "create_time", title: "创建时间", width: 170 },
    {
      title: "操作",
      width: 120,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => ruleEdit(row)} v-hasPermi={[[basicSetupAuthList.custom_fee_items.edit]]}>
                编辑
              </el-button>
              <el-button link type="primary" onClick={() => openLog({ id: row.id })} v-hasPermi={[[basicSetupAuthList.custom_fee_items.log]]}>
                日志
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => queryList({ ...form, ...page }),
    },
  },
})
</script>
<style lang="scss" scoped></style>
